<%@ taglib prefix="s" uri="/struts-tags" %>
<style type="text/css">
    table.new-request-table {
        width: 1000px;
    }

    table.new-request-table select , table.new-request-table input, table.new-request-table textarea{
        width: 98%;
    }

    table.new-request-table textarea, table.new-request-table textarea {
        margin-left: 5px;
        margin-right: 5px;
    }

    table.new-request-table textarea, table.new-request-table input {
        margin-left: 0px;
        margin-right: 5px;
    }

    .opButton {
        width: 80px;
        font-size: 0.8em !important;
    }

    .copyList {
        width: 600px;
        margin-left: 0px;
        height: 100px;
    }

</style>

<form id="requestForm">
    <table class="new-request-table" cellspacing="5" border="0">
        <tr>
            <td class="label"><s:text name="request.category"/></td>
            <td><s:select headerKey="" headerValue="%{getText('pleaseSelect')}" listKey="id" listValue="name"
                          required="true" list="categories" id="category" name="categories" value="category"
                          theme="simple"/>
            </td>
        </tr>
        <tr>
            <td class="label"><s:text name="request.type"/></td>
            <td>
                <s:select headerKey="" headerValue="%{getText('pleaseSelect')}" listKey="id" listValue="name"
                          required="true" list="types" id="type" name="types" theme="simple"/>
            </td>
        </tr>
        <tr>
            <td class="label"><s:text name="request.reporter"/></td>
            <td>
                <s:textfield cssStyle="width: 500px; margin-left: 0px;" theme="simple" name="reporter" id="reporter"
                             readonly="true"
                             value="%{#session.user_context.user.cil}"/>
                <span id="reporterEmail"><s:property value="#session.user_context.user.email"/></span>
            </td>
        </tr>

        <tr>
            <td class="label"><s:text name="request.copyList"/></td>
            <td rowspan="3">
                <s:select cssClass="copyList" theme="simple" name="copyList" multiple="true" list="{}" id="copyList"/>
            </td>
        </tr>
        <tr>
            <td>
                <button class="opButton" id="addCCUser" tabindex="-1"><s:text name="request.add"/></button>
            </td>
        </tr>
        <tr>
            <td>
                <button class="opButton" id="removeCCUser"><s:text name="request.remove"/></button>
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <hr/>
            </td>
        </tr>
    </table>

    <div id="includePage">
        <%--<s:include value="defaultNew.jsp" />--%>
    </div>

    <table border="0" class="new-request-table">
        <tr>
            <td align="center">
                <button id="submit" disabled="true"><s:text name="request.submit"/></button>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <button id="cancel"><s:text name="request.cancel"/></button>
            </td>
        </tr>
    </table>
</form>

<script>
$(function () {
    // fix IE issue
//        var requestForm = $("#requestForm");
    var requestForm = $('#' + global.NEW_REQUEST_TAB_ID);

    var typesFirstOptionValue = $("#type>option:first", requestForm).text();

    /**
     * Make reporter editable if current user is the owner of the category
     * @param categoryId
     * */
    function updateReporter(categoryId) {
        $.post('get-category-owners', {categoryId: categoryId, prop: 'csl, email', idprop: 'csl'}, function (json) {
            $("#reporter", requestForm).prop({"readonly": !json.isOwner});
        });
    }

    $("#selectReportDialog").dialog({
        width: 500,
        height: 300
    });
    var reporterInput = $("#reporter", requestForm);
    var reporterErrMsgDialog = $("<div style='text-align: center;padding-top: 1em'>").dialog({title: "Error", modal: true, autoOpen: false,
        buttons: [
            {text: 'OK', click: function () {
                $(this).dialog("close");
            }}
        ],
        close: function (ui, e) {
            reporterInput.focus().select();
        }
    });

    function updateReport(reporter) {
        if (!reporter || !reporter.csl) return;

        reporterInput.val(reporter.cil).next("#reporterEmail").text(reporter.email);
//        console.log("Save user %o", reporter);
        $.post("save-user-by-csl", {csl: reporter.csl}, function (user) {

            if (!user) {
                $.msgBox($.jgrid.format("Save user {0} to database failed.", reporter.cil), null, {title: "Error"});
            }
        });
    }

    reporterInput.focusout(function (e) {
        e.preventDefault();
        if ($(this).prop("readonly")) return;
        var that = this;
        // validate reporter and query reporter info
        $(this).next("#reporterEmail").html("<img src='images/wait/10.gif'>");
        $.post("validate-reporter", {reporter: this.value}, function (users) {
            $(that).next("#reporterEmail").text("");
            if (0 == users.length) {
                var errorInfo = $.jgrid.format("User '{0}' is not found", that.value);
                reporterErrMsgDialog.empty().append(errorInfo).dialog("open");
                return;
            }

            var toBeSavedUser;
            // if only one user find
            if (1 == users.length) {
                updateReport(users[0]);
                return;
            }
            // if multi users, show the select dialog
            var userLIs = $.map(users,function (user, index) {
                return $.jgrid.format("<li><a href='javascript:void(0)' csl='{0}' >{1}&nbsp;&nbsp;{2}</a></li>", user.csl, user.cil, user.email);
            }).join('\n');
            $("<ul>").width($(that).width()).append(userLIs).menu({
                select: function (event, ui) {
                    var selectedMenuA = $(ui.item.html());
                    console.log(selectedMenuA);
                    var tokens = selectedMenuA.html().split("&nbsp;&nbsp;");
                    var user = {
                        csl: selectedMenuA.attr("csl"),
                        cil: tokens[0],
                        email: tokens[1]
                    };
                    $(this).remove();
                    updateReport(user);
                }
            }).appendTo(document.body).position({my: "left top", at: "left bottom", of: that});
        });
    }).keypress(function(e){
                console.log("Key pressed in reporter Input");
            });

   $("#copyList", requestForm).keypress(function(e){
       console.log("key press in copy list");
   }).click(function(e){
               console.log("click in copy list");
           });


    $("#addCCUser", requestForm).button().click(function (e) {
        e.preventDefault();
        console.log("addCCUser clicked %o", e);
        global.addCCUserDialog.data("requestFrom", requestForm).dialog("open");
    }).keypress(function(e){
                console.log("key press in add user.");
            });

    $("#removeCCUser", requestForm).button().click(function (e) {
        e.preventDefault();
        $('#copyList>option:selected', requestForm).remove();
    });


    $("#type", requestForm).on("change", function (e) {
        if (this.value) {
            var categoryId = $("#category", requestForm).val();
            console.log(
                    $.jgrid.format("Change the page to category id {0}({1}), type id {2}({3})", categoryId,
                            $("#category > option:selected", requestForm).text(), this.value, $("option:selected", this).text()
                    )
            );

            $.blockUI();
            $('#includePage', requestForm).load('get-include-page', {categoryId: categoryId, typeId: this.value}, function (page) {
                $.unblockUI();
                $('#submit', '#requestForm').button("option", "disabled", false);
            });
        }
    });


    var categories = $("#category", requestForm).on("change", function (e) {
        $.post('types', {cid: this.value, prop: 'id, name'}).done(function (types) {
            var types = json2Options($.merge([
                {id: "", name: typesFirstOptionValue}
            ], types), ":first", "name");
            var typesSelect = $("#type", requestForm);
            typesSelect[0].options.length = 0;
            typesSelect.append(types);
        });
        updateReporter(this.value);
    });
    if (categories.val()) {
        updateReporter(categories.val());
    }

    $("#cancel", requestForm).button({
        icons: {
            secondary: "ui-icon-close"
        }
    }).click(function (e) {
                global.closeTab(global.NEW_REQUEST_TAB_ID);
            });
    /**
     * Collect page attributes, and validate
     * */
    global.getAttributes = function (pNames, validateNames) {
        var postData = {};
        for (var i = 0; i < pNames.length; i++) {
            var val = pNames[i];
            postData[val] = $("#" + val, requestForm).val();
        }
//        console.log("Validate create...");
        if (validateNames) {
            for (var i = 0; i < validateNames.length; i++) {
                if (!postData[validateNames[i]]) {
                    var warningName = -1 != validateNames[i].indexOf('_') ? validateNames[i].slice(validateNames[i].indexOf('_') + 1) : validateNames[i].capitalize();
//                    $.msgBox($.jgrid.format("Please input [{0}].", warningName), null, {title: "Error"});
                    $.msgBox($.jgrid.format("[{0}] is required.", warningName), null, {title: "Error"});
                    return;
                }
            }
        }
        return postData;
    }

    $("#submit", requestForm).button({
                icons: {
                    secondary: "ui-icon-disk"
                }
            }
    ).click(function (event) {
                event.preventDefault();
                var pNames = ['category', 'type', 'reporter'];
                var postData = global.getAttributes(pNames);

                var includePostData = global.getIncludeAttributes();
                if (!includePostData) {
                    return;
                }
                //add cc list
                postData.copyList = $('#copyList>option', requestForm).map(function (index, option) {
                    return option.value
                }).get();
                postData = $.extend(postData, includePostData);
//                console.log("postDate = ", postData);

                $.blockUI();
                $.post('new-request', postData, function (json) {
                    $.unblockUI();
                    if (json.status !== 0) {
                        $.msgBox(json.message, null, {
                            title: "Error"
                        });
                        return;
                    }
                    $.msgBox("Request created.", null, {title: "Info"});

                    $('#requestGrid').reloadAll();
                    $('#followupGrid').reloadAll();

                    resetForm();
                    global.closeTab(global.NEW_REQUEST_TAB_ID);
                    $("#tabs").tabs("option", "active", 0);
                    $("#tabs").tabs("refresh");
                });
            });
});

function resetForm() {
    document.forms[0].reset();
    $('#requestAttachmentsGrid').clearGridData()
}

</script>